<?php
// 这是系统自动生成的公共文件


if (!function_exists("success")){
    /**
     * @param $data
     * @param string $msg
     * @param int $code
     * @return \think\response\Json
     */
    function success($data=[],$msg='ok',$code=200){

        $return = [
            'data' => $data,
            'msg' => $msg,
            'code' => $code
        ];
        return json($return);
    }
}


if (!function_exists("fail")){
    /**
     * @param int $code
     * @param string $msg
     * @param array $data
     * @return \think\response\Json
     */
    function fail(int $code=2001, string $msg="参数错误", array $data=[]){

        $return = [
            'data' => $data,
            'msg' => $msg,
            'code' => $code
        ];

        return json($return);
    }
}


if (!function_exists("request_post")) {


    /**
     * 发起http post请求(REST API), 并获取REST请求的结果
     * @param string $url
     * @param string $param
     * @return - http response body if succeeds, else false.
     */
    function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }

        $postUrl = $url;
        $curlPost = $param;
        // 初始化curl
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $postUrl);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // post提交方式
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        // 运行curl
        $data = curl_exec($curl);
        curl_close($curl);

        return json_decode($data,true) ?: [];
    }

}

if (!function_exists("parent_data")) {
    /**
     *
     * @param $data
     * @param int $pid
     * @return array
     */
    function parent_data($data,$pid=0) {
        $res = [];
        foreach ($data as $key => $value) {
            if ($value['pid'] == $pid) {
                $res[$key] = $value;
                $res[$key]['children'] = parent_data($data,$value['id']);
            }
        }
        return $res;
    }
}
